package com.epam.qanda.web.servlet.logged;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.qanda.db.model.QuestionCategory;
import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.QuestionCategoryService;

public class UserQuestionsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Integer COUNT = 20;

	public UserQuestionsServlet() {
		super();

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		User user = (User) request.getSession().getAttribute("user");
		List<QuestionCategory> questions = new QuestionCategoryService().getUserQuestions(user
				.getId());
		Integer offset = 0;
		String off = request.getParameter("offset");
		if (off != null) {
			offset = Integer.parseInt(off.trim());
			request.removeAttribute("offset");
		}

		List<QuestionCategory> newQuestions = new ArrayList<QuestionCategory>();
		for (int i = offset; i < offset + COUNT; i++) {
			if (i < 0 || i >= questions.size())
				continue;
			newQuestions.add(questions.get(i));
		}
		request.setAttribute("action", request.getRequestURI());
		request.setAttribute("questions", newQuestions);
		request.setAttribute("offset", offset);
		request.setAttribute("size", questions.size());
		request.getRequestDispatcher("WEB-INF/pages/questionsPage.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
